package com.test.datasource;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author dengmeiliang
 */
@Aspect
@Order(-1)
@Component
public class DynamicDataSourceAspect {

    private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);


    @Before("@annotation(targetDataSource)")

    public void changeDataSource(JoinPoint point, TargetDataSource targetDataSource) throws Throwable {

        //获取当前的指定的数据源;
        String dsId = targetDataSource.value();

        if (!DynamicDataSourceHolder.existDateSoure(dsId)) {
            logger.error("数据源[{}]不存在，使用默认数据源 > {}" + targetDataSource.value() + point.getSignature());
        } else {
            logger.debug("Use DataSource : {} > {}" + targetDataSource.value() + point.getSignature());
            DynamicDataSourceHolder.setDateSoureType(targetDataSource.value());
        }
    }


    @After("@annotation(targetDataSource)")
    public void cleanDataSource(JoinPoint point, TargetDataSource targetDataSource) {
        logger.info("clean DataSource : {} > {}" + targetDataSource.value() + point.getSignature());

        //方法执行完毕之后，销毁当前数据源信息，进行垃圾回收。
        DynamicDataSourceHolder.clearDateSoureType();

    }

}